package com.hyc.provider;

import com.hyc.serviceRegister.NacosServiceRegister;
import lombok.Getter;

import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 冷环渊
 * @date 2025/6/5 13:58
 * @description provider
 */
public class ServiceProvider {
    private InetSocketAddress serviceAddress;

    //存放接口注册信息的 map
    private Map<String, Object> interfaceProvider;
    private NacosServiceRegister nacosServiceRegister;
    private Map<String, String> nacosMeta;
    @Getter
    private RateLimitProvider rateLimitProvider;

    public ServiceProvider(InetSocketAddress address) {
        this.interfaceProvider = new HashMap<>();
        this.nacosServiceRegister = new NacosServiceRegister(null);
        this.nacosMeta = new HashMap<>();
        this.serviceAddress = address;
        this.rateLimitProvider = new RateLimitProvider();
    }

    public void providerServiceInterface(Object service) {
        Class<?>[] interfaces = service.getClass().getInterfaces();
        for (Class<?> clazz : interfaces) {
            System.out.println(clazz.getName());
            interfaceProvider.put(clazz.getName(), service);
            nacosServiceRegister.register(clazz.getName(), serviceAddress, null, nacosMeta);
        }
    }

    public void providerServiceInterface(Object service, String isRetry) {
        Class<?>[] interfaces = service.getClass().getInterfaces();
        for (Class<?> clazz : interfaces) {
            System.out.println(clazz.getName());
            interfaceProvider.put(clazz.getName(), service);
            nacosMeta.put(clazz.getName(), isRetry);
            nacosServiceRegister.register(clazz.getName(), serviceAddress, null, nacosMeta);
        }
    }

    public void providerServiceInterface(String interfaceName, Object service, String isRetry) {
        Class<?>[] interfaces = service.getClass().getInterfaces();
        for (Class<?> clazz : interfaces) {
            System.out.println(clazz.getName());
            interfaceProvider.put(interfaceName, service);
            nacosMeta.put(interfaceName, isRetry);
            nacosServiceRegister.register(interfaceName, serviceAddress, null, nacosMeta);
        }
    }

    public Object getService(String interfaceName) {
        return interfaceProvider.get(interfaceName);
    }
}
